package com.example.interceptors;

import com.example.annotations.RequiredToken;
import com.example.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * @Author: hx
 * @CreateTime: 2022/3/4 09:47
 * @Description:
 * */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取当前方法是否存在@RequiredToken注解
        boolean requiredToken = ((HandlerMethod) handler).getMethod().isAnnotationPresent(RequiredToken.class);
        //2.存在该注解
        if (requiredToken){
            //1.获取token信息
            String token = request.getParameter("token");
            log.info("当前传递的token信息是{}",token);
            //拼接前缀，和redis存储一致
            String tokenKey="session_"+token;
            //根据token获取用户信息
            User user = (User) redisTemplate.opsForValue().get(tokenKey);
            if (user==null) throw new RuntimeException("提示：令牌无效，token失效");
            //存档到当前请求的上下文中
            request.setAttribute("token",token);
            request.setAttribute("user",user);
        }
        return true;
    }
}
